Introduction to Machine Learning

Unit 24: Partitional Clustering (K-Means) + Evaluation

1. Introduction

This unit dives deep into the most widely used partitional clustering algorithm: K-Means Clustering. We study its optimization objective, the two-step (assignment + update) algorithm, the initialization problem and solutions (multiple restarts, Bisecting K-Means), and then switch gears to evaluation measures: Within/Between Sum of Squares, the Elbow Curve, and the Silhouette Coefficient.

Learning Objectives

Today's Agenda

  1. Recap of the Previous Lecture
  2. K-Means algorithm and objective
  3. Choosing Initial Centroids & Initialization sensitivity
  4. Bisecting K-Means
  5. Clustering Evaluation: Intrinsic Measures
  6. Within & Between Sum of Squares (WSS, BSS, TSS)
  7. Elbow / Scree Plot
  8. Silhouette Coefficient and average silhouette width

2. Theory

2.1 K-Means Objective: Within-Cluster Sum of Squares

K-Means partitions n data points into K clusters where each point belongs to the cluster with the nearest centroid (mean). Its objective is to minimize the Within-Cluster Sum of Squares (WSS), also called the Sum of Squared Errors (SSE):

\[ \text{WSS} = \sum_{i=1}^{K} \sum_{x \in C_i} \| x - \mu_i \|^2 \]

where:

Intuition: Find K centroids such that each point is as close as possible to its assigned cluster centroid. K-Means is an iterative optimization algorithm: it starts with K initial centroids and alternates between two steps until convergence.

2.2 K-Means Algorithm Step-by-Step

  1. Input: Dataset \( D = \{x_1, x_2, \dots, x_n\} \), number of clusters K.
  2. Output: K clusters and their centroids.
  3. 1. Initialize: Select K initial centroids \( \{\mu_1, \mu_2, \dots, \mu_K\} \) (randomly or via heuristic).
  4. 2. Repeat until convergence:
  5.    a) Assignment step: For each point \( x_i \), assign it to cluster \( j^* = \arg\min_j \| x_i - \mu_j \|^2 \).
  6.    b) Update step: For each cluster \( C_j \), recompute its centroid \( \mu_j = \frac{1}{|C_j|} \sum_{x \in C_j} x \).
  7. 3. Convergence criteria (any of): Centroids don't change (or change < threshold); max iterations reached; WSS doesn't decrease significantly.
K-Means: 2-Step Cycle Until Convergence A flow diagram showing the assignment and update steps of the K-means algorithm, repeated until convergence. K-MEANS 2-STEP CYCLE UNTIL CONVERGENCE A ASSIGNMENT Each xᵢ → nearest μⱼ (hard assignment) B UPDATE μⱼ = mean(Cⱼ) (move centroid to mean) Converged? check centroids YES DONE NO repeat cycle
K-Means Visual Iterations on 2D Blobs Three visual iterations show centroid markers moving toward stable clusters of two-dimensional data points, followed by convergence. K-Means Visual Iterations Centroids move toward the center of their assigned 2D data blobs CENTROIDS × μ₁ + μ₂ μ₃ Iteration 1 Initial centroid placement × + reassign Iteration 2 Centroids move toward local means × + update Iteration 3 Stable assignments and centroids × + Converged no change in μ μ = centroid Centroids drift each iteration while point assignments stabilize.

2.3 The Initialization Problem

K-Means is very sensitive to the choice of initial centroids. This matters because K-Means finds a local optimum, not necessarily the global optimum. Different starting points can therefore produce different final clusterings. Poor initialization can produce:

Two different K-means clusterings with K equals 3 A comparison of a sub-optimal clustering with high within-cluster sum of squares and an optimal clustering with low within-cluster sum of squares. TWO DIFFERENT K-MEANS CLUSTERINGS Same data · K = 3 · Different starting centroids can produce different outcomes Cluster 1 Cluster 2 Cluster 3 SUB-OPTIMAL LOCAL MINIMUM μ● μ▲ μ◆ centroid trapped away from the true blob center Centroids settle in a local minimum. Clusters are less compact and overlap the true structure. WSS = 48.3 higher within-cluster variance OPTIMAL BEST FIT μ● μ▲ μ◆ centroid aligned with the true blob Centroids align with the natural data blobs. Clusters are compact and well separated. WSS = 21.7 lower within-cluster variance better fit

2.4 Solutions to the Initialization Problem

Strategy 1: Multiple Random Restarts
Strategy 2: Bisecting K-Means

2.5 Bisecting K-Means Algorithm

  1. Initialize: Place all data points in a single cluster.
  2. Repeat until K clusters are obtained:
  3.    a) Select cluster to split: Choose by one of:
    • Largest WSS / SSE (most internal variance)
    • Largest number of data points
    • Random selection (less common)
  4.    b) Bisect the selected cluster:
    • Run basic K-Means with K=2 on the selected cluster.
    • Perform multiple trials with different random initializations.
    • Keep the bisection with lowest total SSE.
  5.    c) Update cluster list: Remove the original cluster; add the two sub-clusters.
  6. Terminate when the desired K is reached.
Bisecting K-Means from K equals 1 to K equals 4 A staged diagram showing clusters being split by local two-means problems until four clusters are formed. BISECTING K-MEANS Progressive splitting from K = 1 to K = 4 K = 1 Initial cluster split biggest WSS cluster K = 2 First bisection split left cluster · WSS larger K = 3 Second bisection split rightmost K = 4 Final clusters Each split is a local 2-means problem → simpler and more stable optimization

2.6 Evaluating Clustering Results

Evaluation is tricky in clustering because there is no single "right answer." The goal is to compare different clustering experiments and select a good configuration. Two families of measures exist:

Internal (Intrinsic) Measures
External (Extrinsic) Measures

2.7 Internal Measures: Cohesion vs Separation

Formal definitions: Let \(|C_i|\) = size of cluster \(i\), \(m_i\) = centroid of cluster \(i\), and \(m\) = the overall (global) mean of all data points.

\[ \text{WSS} = \sum_{i=1}^{K} \sum_{x \in C_i} \| x - m_i \|^2 \]
\[ \text{BSS} = \sum_{i=1}^{K} |C_i| \cdot \| m_i - m \|^2 \]

Key identity: Total Sum of Squares TSS = WSS + BSS, always, for any partition. TSS is constant for the dataset.

\[ \text{TSS} = \sum_{\text{all } x} \| x - m \|^2 = \text{WSS} + \text{BSS} \]

2.8 Cohesion & Separation: Numerical Example

Toy 1D dataset of 5 points: {1, 2, 3, 4, 5}

Case K=1 (all in one cluster, m = (1+2+3+4+5)/5 = 3):

\[ \text{WSS} = (1{-}3)^2 + (2{-}3)^2 + (3{-}3)^2 + (4{-}3)^2 + (5{-}3)^2 = 4 + 1 + 0 + 1 + 4 = 10 \] \[ \text{BSS} = 5 \times (3 - 3)^2 = 0 \] \[ \text{Total} = 10 + 0 = 10 \]

Case K=2 (clusters C1={1,2}, C2={3,4,5}; m1=1.5, m2=4):

\[ \text{WSS} = \underbrace{(1{-}1.5)^2 + (2{-}1.5)^2}_{0.25+0.25=0.5} + \underbrace{(3{-}4)^2 + (4{-}4)^2 + (5{-}4)^2}_{1+0+1=2} = 2.5 \] \[ \text{BSS} = |C_1|\|m_1{-}m\|^2 + |C_2|\|m_2{-}m\|^2 = 2 \times (1.5{-}3)^2 + 3 \times (4{-}3)^2 = 2 \times 2.25 + 3 \times 1 = 4.5 + 3 = 7.5 \] \[ \text{Total} = 2.5 + 7.5 = 10 \quad \checkmark \quad (\text{Same TSS!}) \]

2.9 Elbow / Scree Plot

To choose K, vary the number of clusters and plot total within-cluster SSE vs K. Look for an elbow: the K after which the drop in WSS sharply flattens. That elbow represents a good balance between explanatory power (low WSS) and model simplicity (small K).

Elbow plot: WSS versus K A scree plot showing a steep reduction in within-cluster sum of squares through K equals 3, followed by smaller reductions. K equals 3 is highlighted as the elbow or sweet spot. ELBOW (SCREE) PLOT Within-cluster sum of squares by number of clusters 0 2 4 6 8 10 12 1 2 3 4 5 6 7 WSS K ELBOW AT K = 3 Best balance of fit and simplicity Interpretation The WSS drops sharply through K = 3. After that point, each additional cluster gives very little reduction. RECOMMENDED K 3 sweet spot Model selection heuristic · Lower WSS indicates tighter clusters

Caution: Sometimes there is no clear elbow. Even when there is, interpretation and decision remain somewhat subjective.

2.10 Silhouette Coefficient

The Silhouette Coefficient evaluates every single point individually: how well is it located inside its own cluster, versus how separated it is from the other clusters? Works with any distance metric.

For each point \(d_i\) currently assigned to cluster \(C_i\):

  1. Compute \(a_i\): the average dissimilarity (distance) of \(d_i\) to all other objects in the same cluster \(C_i\). Small \(a_i\) is good: the cluster is tight/homogeneous.
  2. For every other cluster \(C_j\) (\(j \neq i\)), compute the average distance from \(d_i\) to all objects in \(C_j\). The minimum of these averages is called \(b_i\): \[ b_i = \min_{j \neq i} \text{avg}_{x \in C_j} d(d_i, x) \] \(b_i\) tells us how close \(d_i\) is to the nearest competing cluster. Larger is better!
  3. Point silhouette for \(d_i\):
    \[ s(i) = \frac{b_i - a_i}{\max(a_i, b_i)} \]

Interpretation of s(i)

s(i) near…Meaning
+1ai << bi. Point is very well clustered: tight inside its cluster, far from competitors.
0ai ≈ bi. Point lies exactly on the decision boundary between its best and second-best cluster.
-1ai >> bi. Point is likely mis-assigned: would be more similar on average if moved to its neighboring cluster.

Aggregate Silhouette Summaries

Cost: Silhouette requires O(n²) distance evaluations — computationally expensive for larger datasets.

How Silhouette Changes with Wrong K

3. Interactive Examples

Example 1: Centroid Update Calculation

After the assignment step of 2D K-Means, cluster C3 contains three points: \( x_1 = (1, 2) \), \( x_2 = (3, 0) \), \( x_3 = (5, 4) \). What is the new centroid \( \mu_3 \) after the update step?

Component-wise mean:

\[ \mu_3 = \left(\frac{1+3+5}{3},\ \frac{2+0+4}{3}\right) = \left(\frac{9}{3},\ \frac{6}{3}\right) = (3,\ 2) \]

Example 2: Empty Cluster Scenario

You run K-Means with K=4 on a 2D dataset that naturally only has 3 blobs. What outcome is plausible for the 4th centroid, and how would you fix it?

Reveal Answer

Plausible outcomes:

  1. Empty cluster: the 4th centroid never "wins" any point during assignment → its updated location becomes undefined.
  2. Absorb a few outliers from one of the real blobs, splitting that blob artificially and inflating WSS.

Standard fix in libraries:

  • Re-initialize the empty-cluster centroid to the point farthest from its current centroid (most misrepresented point), or to the point with highest contribution to WSS from within the largest cluster.
  • The better solution: lower K and use the Elbow / Silhouette to justify it.

Example 3: WSS+BSS Identity

A clustering on 1D dataset {1,3,5,7,9,11} with K=3 yields clusters C1={1,3}, C2={5,7}, C3={9,11}. Without computing WSS and BSS individually, what MUST be the numerical value of WSS + BSS?

WSS + BSS = TSS (always!). Global mean m = (1+3+5+7+9+11)/6 = 6.

\[ \text{TSS} = (1{-}6)^2 + (3{-}6)^2 + (5{-}6)^2 + (7{-}6)^2 + (9{-}6)^2 + (11{-}6)^2 \] \[ = 25 + 9 + 1 + 1 + 9 + 25 = 70 \]

Therefore WSS + BSS = 70, regardless of the partition.

Example 4: Silhouette Interpretation

Two different K values are tried on the same dataset:

Which K is better supported by silhouette evidence? Why?

Reveal Answer

K=2 is clearly better. ASW of 0.72 is high and the per-cluster silhouettes are wide → strong evidence of compact, well-separated clusters. K=5's ASW of 0.18 plus the near-zero / negative individual silhouettes indicates K=5 is too high — natural clusters are being split, causing points to be close to multiple competing centroids.

4. Numerical Solutions

Problem 1: K-Means Manual Iteration

Run ONE full iteration (assignment + update) of 2D K-Means with K=2.

Dataset: { A(1,1), B(2,1), C(4,3), D(5,4) }

Initial centroids: \( \mu_1^{(0)} = (1,0) \), \( \mu_2^{(0)} = (6,5) \)

📘 Step-by-Step Solution

Step A: Assignment (squared Euclidean distance to each centroid):

Point‖x-μ₁‖²‖x-μ₂‖²Assigned cluster
A(1,1)(1-1)²+(1-0)²=1(1-6)²+(1-5)²=25+16=41C1
B(2,1)(2-1)²+(1-0)²=1+1=2(2-6)²+(1-5)²=16+16=32C1
C(4,3)(4-1)²+(3-0)²=9+9=18(4-6)²+(3-5)²=4+4=8C2
D(5,4)(5-1)²+(4-0)²=16+16=32(5-6)²+(4-5)²=1+1=2C2

→ C1 = {A, B}, C2 = {C, D}.

Step B: Centroid Update:

\[ \mu_1^{(1)} = \left(\frac{1+2}{2},\ \frac{1+1}{2}\right) = (1.5,\ 1.0) \] \[ \mu_2^{(1)} = \left(\frac{4+5}{2},\ \frac{3+4}{2}\right) = (4.5,\ 3.5) \]

End of iteration 1. New centroids: μ₁=(1.5, 1.0), μ₂=(4.5, 3.5). Next iteration repeats Step A with these centroids.

Problem 2: WSS, BSS, TSS from scratch

1D dataset: {2, 4, 6, 8, 10, 12}. Clustering into C1={2,4,6}, C2={8,10,12}. Compute WSS, BSS, and TSS. Verify the identity TSS = WSS + BSS.

📘 Step-by-Step Solution

Step 1: Global mean m = (2+4+6+8+10+12)/6 = 42/6 = 7.

Step 2: TSS.

\[ \text{TSS} = \sum (x_i - m)^2 = (2{-}7)^2 + (4{-}7)^2 + (6{-}7)^2 + (8{-}7)^2 + (10{-}7)^2 + (12{-}7)^2 \] \[ = 25 + 9 + 1 + 1 + 9 + 25 = 70 \]

Step 3: Cluster centroids. m1 = (2+4+6)/3 = 4; m2 = (8+10+12)/3 = 10.

Step 4: WSS.

\[ \text{WSS}(C1) = (2{-}4)^2 + (4{-}4)^2 + (6{-}4)^2 = 4 + 0 + 4 = 8 \] \[ \text{WSS}(C2) = (8{-}10)^2 + (10{-}10)^2 + (12{-}10)^2 = 4 + 0 + 4 = 8 \] \[ \text{WSS} = 8 + 8 = 16 \]

Step 5: BSS.

\[ \text{BSS} = 3 \times (4{-}7)^2 + 3 \times (10{-}7)^2 = 3 \times 9 + 3 \times 9 = 27 + 27 = 54 \]

Step 6: Verify.

\[ \text{WSS} + \text{BSS} = 16 + 54 = 70 = \text{TSS} \quad \checkmark \]

Problem 3: Silhouette of a 3-point cluster

1D dataset clustered into two clusters: Cluster X = {1, 2, 7} and Cluster Y = {12, 13}. Compute the silhouette s(3) for the point at x = 7 (currently in Cluster X). Use Manhattan distance: d(p, q) = |p - q|.

📘 Step-by-Step Solution

Target point = p = 7 in cluster X = {1,2,7}. Other cluster Y = {12,13}.

Step 1: a_i (avg distance within X, excluding p itself):

Distances from 7 to others in X: |7-1|=6, |7-2|=5. Average = (6+5)/2 = 5.5.

→ a_i = 5.5.

Step 2: b_i (min over other clusters of avg distance to that cluster):

Avg distance from 7 to all of Y: (|7-12|+|7-13|)/2 = (5+6)/2 = 5.5.

→ b_i = 5.5.

Step 3: s(i) = (b_i - a_i) / max(a_i, b_i):

\[ s(7) = \frac{5.5 - 5.5}{\max(5.5,\ 5.5)} = \frac{0}{5.5} = 0 \]

Interpretation: s = 0 means this point sits exactly on the decision boundary between the two clusters. It could belong to either with equal justification on average.

5. Try It Yourself

Practice 1: 2nd K-Means Iteration

Using the result of Problem 1 (Section 4):

Perform the assignment step only of iteration 2. Verify whether any point switches cluster membership, and report the resulting C1, C2 sets.

Point‖x-μ₁‖²=(x-1.5)²+(y-1)²‖x-μ₂‖²=(x-4.5)²+(y-3.5)²Cluster
A(1,1)(-0.5)²+0=0.25(-3.5)²+(-2.5)²=12.25+6.25=18.50C1
B(2,1)0.5²+0=0.25(-2.5)²+(-2.5)²=6.25+6.25=12.50C1
C(4,3)2.5²+2²=6.25+4=10.25(-0.5)²+(-0.5)²=0.25+0.25=0.50C2
D(5,4)3.5²+3²=12.25+9=21.250.5²+0.5²=0.25+0.25=0.50C2

Assignment unchanged. C1={A,B}, C2={C,D}. No switches → algorithm has converged.

Practice 2: Silhouette of an outlier

Same data as Problem 3 (Section 4): 1D points with Manhattan distance. Clusters X = {1, 2, 7}, Y = {12, 13}. Compute s(1) for the point at 1 (in X).

a_i: distances from point=1 to {2, 7} = |1-2|=1 and |1-7|=6. Average = (1+6)/2 = 3.5.

b_i: avg distance to Y = {12,13}: (|1-12| + |1-13|)/2 = (11+12)/2 = 11.5.

\[ s(1) = \frac{11.5 - 3.5}{\max(3.5, 11.5)} = \frac{8}{11.5} \approx 0.696 \]

→ ~0.70, so the point at 1 is reasonably well clustered.

Practice 3: Bisecting K-Means trace

Suppose 6 points have TSS=120 when K=1. We want to reach K=3 using Bisecting K-Means. First split (K=2) splits into cluster A (WSS=28, 4 points) and cluster B (WSS=15, 2 points). Which cluster is selected next to split, under the "largest WSS" criterion? What will the total WSS of K=3 be, assuming the chosen cluster splits into two halves with total new WSS=10?

  1. Selection rule (largest WSS): Cluster A has WSS 28, which is larger than cluster B's WSS 15. So cluster A is split next.
  2. Total WSS at K=3: When we split A into A1+A2 with WSS 10, we remove A's old WSS of 28 and add the new sub-WSS of 10. Cluster B's WSS stays 15:
    \[ \text{WSS}_{K=3} = \underbrace{10}_{\text{split of } A} + \underbrace{15}_{\text{untouched } B} = 25 \]

6. Interactive Quiz

Your score: 0 / 5

7. Key Takeaways

  1. K-Means minimizes the WSS objective \( \sum_{i=1}^{K}\sum_{x\in C_i}\|x-\mu_i\|^2 \) via a two-step iterative loop: assignment (points → nearest centroid) then update (centroid = mean of cluster).
  2. K-Means only finds a local optimum; initialization matters — use multiple random restarts (pick min WSS) or Bisecting K-Means for stability.
  3. Bisecting K-Means: Start with one cluster; repeatedly 2-means-split the largest-WSS cluster until K clusters; less sensitive to initialization.
  4. Internal evaluation = no labels needed. WSS measures cohesion; BSS measures separation. Identity: WSS + BSS = TSS (always).
  5. Elbow plot of WSS vs K: choose K at the elbow where rate of WSS drops sharply flattens.
  6. Silhouette coefficient s(i) = (b_i - a_i)/max(a_i, b_i) for each point. Range [-1, +1]. High positive = well clustered. Near 0 = on boundary. Negative = likely mis-clustered.
  7. Average Silhouette Width (ASW) peaks at good K; but silhouette is O(n²) and slow on big data.

8. Common Pitfalls

  1. Running K-Means ONCE with random init and trusting it: K-Means is not deterministic! Always run multiple restarts or use Bisecting K-Means / k-means++ (sklearn default).
  2. Forgetting to STANDARDIZE features before K-Means: K-Means is based on Euclidean distance, so unscaled features (e.g., income in $ vs. age in years) dominate the geometry incorrectly.
  3. Using WSS alone: WSS monotonically decreases with K and reaches 0 when K=n. It must be compared to BSS, used in an Elbow plot, or traded off with a penalty (silhouette / gap statistic).
  4. Silhouette sign confusion: (b − a), not (a − b). When b < a, s(i) is negative, not positive.
  5. Misinterpreting empty BSS at K=1: BSS=0 is correct at K=1 (the single centroid equals the global mean). Total TSS = WSS only.
  6. Applying K-Means to non-convex / non-spherical data: K-Means is built on squared Euclidean centroid dispersion. It splits arbitrarily shaped clusters unnaturally (use DBSCAN instead, covered in Unit 25).

9. Resources